﻿var oldWidth;
var oldHeight;
$(function () {
	$('#photo').imgAreaSelect({
		aspectRatio: '1:1', 
		handles: true,
		fadeSpeed:300, 
		onSelectChange: preview });
});
var resetImg = function(){
    oldWidth = $('#photo').attr("width");
    oldHeight = $('#photo').attr("height");
	if($('#photo').attr("width")>500){
		$('#photo').attr("width",500);
		$('#photo').attr("height",500*$('#photo').attr("height")/$('#photo').attr("width"));
	}
}
var preview = function (img, selection) {
	if (!selection.width || !selection.height)
		return;
	var scaleX = 100 / selection.width;
	var scaleY = 100 / selection.height;
	$('#preview img').css({
		width: Math.round(scaleX * $('#photo').attr("width")),
		height: Math.round(scaleY * $('#photo').attr("height")),
		marginLeft: -Math.round(scaleX * selection.x1),
		marginTop: -Math.round(scaleY * selection.y1)
	});
	if(oldWidth<=500){
	    $('#x1').val(selection.x1);
	    $('#y1').val(selection.y1);
	    $('#x2').val(selection.x2);
	    $('#y2').val(selection.y2);
	}
	else{
	    var scaleWidth = oldWidth/$('#photo').attr("width");
	    var scaleHeight = oldWidth/$('#photo').attr("width");
	    $('#x1').val(selection.x1*scaleWidth);
	    $('#x2').val(selection.x2*scaleWidth);
	    $('#y1').val(selection.y1*scaleHeight);
	    $('#y2').val(selection.y2*scaleHeight);
	}
}